<template>
  <Form ref="validForm" :model="formData" :rules="ruleValidate">
    <Row :gutter="32">
      <Col span="18">
        <!--  设置图片允许最大4M -->
        <Upload
            ref="upload"
            :show-upload-list="false"
            :format="['jpg','jpeg','png']"
            :max-size="4096"
            name="avatar"
            accpet="image/*"
            :headers="{Authorization: 'Bearer ' + $store.state.token}"
            :default-file-list="defaultList"
            type="drag" :on-success="handleSuccess"
            :on-exceeded-size="handleExceededSize"
            :action="$api.uploadUrl()"> <!-- 设置上传头像后台地址 -->
          <div style="padding: 20px 0">
            <Icon type="ios-camera" size="52" style="color: #3399ff"></Icon>
            <p>请上传用户头像</p>
          </div>
        </Upload>
      </Col>
      <Col span="6">
        <div class="demo-upload-list" v-for="item in uploadList">
          <template v-if="item.status === 'finished'">
            <Image :src="item.url" fit="cover" width="100%" height="100%"/>
          </template>
          <template v-else>
            <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
          </template>
        </div>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="用户名" label-position="top" prop="username" :error="error.username">
          <Input v-model="formData.username" placeholder="请输入用户名"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="初始默认密码" label-position="top" prop="password" :error="error.password">
          <Input v-model="formData.password" placeholder="请输入密码" />
        </FormItem>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="真实姓名" label-position="top" prop="realName" :error="error.realName">
          <Input v-model="formData.realName" placeholder="请输入真实姓名"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="手机号" label-position="top" prop="tel" :error="error.tel">
          <Input v-model="formData.tel" placeholder="请输入手机号"/>
        </FormItem>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="所属组织机构" label-position="top" prop="orgs" :error="error.orgs">
          <TreeSelect v-model="formData.orgs" multiple show-checkbox :data="orgList"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="电子邮箱" label-position="top" prop="email" :error="error.email">
          <Input v-model="formData.email" placeholder="请输入电子邮箱"/>
        </FormItem>
      </Col>
    </Row>


    <Row :gutter="32">
      <Col span="12">
        <FormItem label="职务" label-position="top">
          <Select v-model="formData.positions" multiple>
            <Option v-for="item in positions" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>

      <Col span="12">
        <FormItem label="性别" label-position="top">
          <Select v-model="formData.sex">
            <Option v-for="item in sexList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>
    </Row>


    <Row :gutter="32">
      <Col span="12">
        <FormItem label="出生日期" label-position="top">
          <DatePicker type="date" v-model="formData.birth" style="width: 100%;"
                      placeholder="请选择出生日期" :options="options"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="用户状态" label-position="top" prop="state">
          <Select v-model="formData.state">
            <Option v-for="item in state" :value="item.value" :key="item.label">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>
    </Row>


  </Form>

  <div class="demo-drawer-footer">
    <Button style="margin-right: 8px" @click="$emit('close-win', false)">关闭</Button>
    <Button type="primary" @click="handleForm">保存</Button>
  </div>
</template>

<script>
export default {
  props: {
    userId: {type: Number, required: false},
  },
  data() {
    return {
      error: {},
      formData: {
        username: "",
        password: "123456",
        realName: "",
        tel: "",
        orgs: [],
        positions: [],
        sex: "",
        birth: "",
        email: "",
        state: 1,
        avatar: "", // 上传的头像名
      },
      defaultList: [{url: new URL("@/assets/default-user.png", import.meta.url).href}], // 默认头像，修改的时候使用
      uploadList: [],
      orgList: [],
      positions: [],
      state: [{value: 1, label: "启用"}, {value: 0, label: "禁用"}],
      sexList: [
        {value: "m", label: "男"}, {value: "f", label: "女"},
      ],
      options: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      ruleValidate: {
        username: [
          {required: true, message: "用户名不允许为空", trigger: 'blur'},
          {type: "string", max: 100, message: "用户名过长", trigger: 'blur'},
          {type: "string", pattern: /^\w+$/, message: "用户名只允许字母、数字和下划线组成", trigger: 'blur'},
        ],
        realName: [
          {required: true, message: "真实姓名不允许为空", trigger: 'blur'},
          {type: "string", max: 30, message: "真实姓名过长", trigger: 'blur'},
        ],
        tel: [
          {required: true, message: "手机号不允许为空", trigger: 'blur'},
          {type: "string", pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: 'blur'},
        ],
        orgs: [
          {required: true, type: "array", min: 1, message: "至少选择一个组织机构", trigger: 'change'},
        ],
        password: [
          {
            validator:(rule, value, callback)=>{
              if (this.userId == null && value === "") { // 如果当前用户是空的，则密码必传
                return callback(new Error("密码不允许为空"));
              }
              callback();
            },
            trigger: 'blur'
          }
        ],
        email: [
          {required: true, message: "邮箱不允许为空", trigger: 'blur'},
          {
            type: "string",
            pattern: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,
            message: "邮箱格式不正确",
            trigger: 'blur'
          },
        ],
        state: [
          {type: "enum", enum: [0, 1], message: "状态必须是一个boolean类型的值", trigger: "blur"}
        ],
      }
    }
  },
  created() {
    // 查询 组织机构, 职务, 和 用户信息
    this.queryData();
  },
  emits: ["close-win"],
  methods: {
    queryData() {
      this.$api.queryOrgAndPositionOrUserData(this.userId).then(ret => {
        // 模拟异步
        if (ret.data.status) {

          if (this.userId != null) { // 如果用户ID 不为空，则查询用户信息，并进行回显
            this.formData = ret.data.data.user ;
            if (this.formData.avatar == null) {
              this.defaultList = [{url: new URL("@/assets/default-user.png", import.meta.url).href}]
            }else{
              this.defaultList = [ {url: this.$api.previewPath(this.formData.avatar)} ]
            }
            this.uploadList = [...this.defaultList] ;
            // 下拉列表不支持 boolean 状态的值
            if(this.formData.state) {
               this.formData.state = 1 ;
            }else{
              this.formData.state = 0 ;
            }
          }
          // 将 接口中返回的职务数据 绑定到响应式数据中
          this.positions = ret.data.data.positions.map(pos => ({value: pos.id, label: pos.name}));
          // 将 和 当前用户绑定的职务 查询出来，并添加到 formData.positions 中
          this.formData.positions = ret.data.data.positions.filter(p => p.bind).map(p => p.id);

          this.formData.orgs = ret.data.data.organizations.filter(p => p.bind).map(p => p.id);
          // 获取接口中的组织机构信息，绑定到响应式数据中
          this.orgList = this.covertOrganization(ret.data.data.organizations, null);

        }
      })
    },
    covertOrganization(data, pid) { // 查询 pid 对应的所有组织机构
      // 获取 pid 对应的组织机构
      let orgList = data.filter(org => org.pid == pid);
      // 遍历 一级组织机构 ，获取 二级组织机构
      return orgList.map(org => {
        // 查询 二级组织机构
        let children = this.covertOrganization(data, org.id);
        return {
          title: org.name, expand: true, value: org.id, checked: org.bind, children
        }
      });

    },
    handleSuccess(response, file, fileList) {
      // 从响应中 获取 上传图片的地址
      file.url = response.data.url;
      this.formData.avatar = response.data.name;
      this.uploadList = [file];
    },
    handleExceededSize(file, fileList) {
       this.$tips.warning("您选择的图片过大、");
    },
    handleForm() {
      this.error = {}
      this.$refs.validForm.validate(valid => {
        if (valid) {
          if (this.userId == null) {
            this.handleSave();
          } else {
            this.handleUpdate();
          }
        }
      })
    },
    handleSave() {
      this.$api.addUser({...this.formData, birth: this.birthday}).then(ret=> {
         if (ret.data.status) {
           this.$tips.success("保存用户成功");
           this.$emit("close-win", "save");
         }else{
            this.error = ret.data.error ;
         }
      })
    },
    handleUpdate() {
      this.$api.updateUser({...this.formData, birth: this.birthday}).then(ret=> {
        if (ret.data.status) {
          this.$tips.success("修改用户成功");
          this.$emit("close-win", "update");
        }else{
           this.error = ret.data.error ;
        }
      })
    },
    resetValidForm() {
      this.$refs.validForm.resetFields();
      this.error = {}
    },

  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
  },
  computed: {
     birthday() {
        let birth = this.formData.birth ;
        if (birth != null && birth != "") {
          return this.$Date(birth).format("YYYY-MM-DD")
        }
        return birth ;
     }
  }
}
</script>

<style scoped>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}

.demo-upload-list {
  display: inline-block;
  width: 113px;
  height: 113px;
  text-align: center;
  line-height: 113px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>